package cfengMiddleware.server.rabbitmq.producer;

import cfengMiddleware.server.rabbitmq.entity.MessageEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author Cfeng
 * @date 2022/9/23
 */

@Component
@RequiredArgsConstructor
@Slf4j
@EnableScheduling
public class RedissonDelayQueuePublisher {

    private final RedissonClient redissonClient;

    //发布消息进入延迟队列
    public void sendDelyMsg(MessageEntity messageEntity,Long ttl) {
        //定义延迟队列的名称
        final String delayQueueName = "redissonDelayQueueV3";

        //定义阻塞队列组件
        RBlockingDeque<MessageEntity> rBlockingDeque = redissonClient.getBlockingDeque(delayQueueName);
        //定义获取延迟队列实例
        RDelayedQueue<MessageEntity> rDelayedQueue = redissonClient.getDelayedQueue(rBlockingDeque);
        //延迟队列以阻塞队列为参数，先将消息放入阻塞队列阻塞住
        //将消息放入延迟队列，设置ttl，会按照TTL排序
        try {
            rDelayedQueue.offer(messageEntity,ttl, TimeUnit.SECONDS);
            log.info("延迟队列Redisson 生产者 {}",messageEntity);
        } catch (Exception e) {
            log.error("延迟队列Redisson 生产者Error, {}",e.fillInStackTrace());
        }
    }
}
